//
//  HeapListViewService.m
//  ChongDingTest
//
//  Created by luyee on 2020/9/2.
//  Copyright © 2020 luyee. All rights reserved.
//

#import "HeapListViewService.h"
#import "HeapListModels.h"
#import "Request.h"

@implementation HeapListViewService {
    HeapListModel *_model;
}

- (void)setContent:(NSString *)content {
    if (_content != content) {
        _content = content;
        self.pageNumber = 0;
        [self requestWithKey:content];
    }
}

- (void)loadMore {
    if (self.dataSource.count < _model.list.count / 5) {
        [self requestWithKey:self.content];
    }
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataSource;
}

- (void)requestWithKey:(NSString *)key {
    __weak typeof(self) weakSelf = self;
    self.pageNumber += 1;
    if (self.pageNumber == 1) {
        [self.dataSource removeAllObjects];
    }

    [Request request:@"https://image.so.com/j"
          withParams:@{@"sn": @((self.pageNumber - 1) * 50), @"pn": @(self.pageNumber * 50), @"q": key}
             success:^(Class  _Nonnull __unsafe_unretained model) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if ([model isKindOfClass:HeapListModel.class]) {
            strongSelf->_model = (HeapListModel *)model;
            [strongSelf.dataSource addObjectsFromArray:strongSelf->_model.list];
            [strongSelf.viewCtrl refresh];
            
            NSLog(@"完成，%ld", self->_model.list.count);
        }
    }];
}

@end
